package com.projectx.action.talk;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.google.gson.Gson;
import com.projectx.R;
import com.projectx.action.MainActivity;
import com.projectx.dao.UserDataDao;
import com.projectx.entity.User;
import com.projectx.util.ActivityManage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class IdentityFragment extends Fragment {
    private Button changeAccount;
    private Button exitAccount;
    private ImageView refreshPic;
    private TextView textView;
    private ImageView headView;
    private FileInputStream pictureIn;
    private Uri headImageUri;
    private String username;
    private User userData;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_identity,container,false);
        changeAccount = view.findViewById(R.id.identityChangeAccount);
        exitAccount = view.findViewById(R.id.identityExitAccount);
        textView = view.findViewById(R.id.identityAccountName);
        headView = view.findViewById(R.id.identityAccountImage);
        refreshPic = view.findViewById(R.id.refreshPic);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (IdentityFragment.this.getActivity() != null) {
            username = IdentityFragment.this.getActivity().getIntent().getStringExtra("accountName");
            textView.setText(username);

            new Thread(userInfo).start();
            headView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                    alert.setTitle("请选择").setMessage("请不要上传过大的头像，尽量在2M以下")
                            .setNeutralButton("取消",null)
                            .setNegativeButton("上传头像", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                    intent.setType("image/*");
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    startActivityForResult(intent,1);
                                }
                            })
                            .setPositiveButton("查看头像", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    final ImageView bigImage = new ImageView(getActivity());
                                    bigImage.setBackgroundColor(Color.TRANSPARENT);
                                    Glide.with(getActivity()).load(headImageUri).into(bigImage);
                                    final WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);//调用windowmanage显示图片
                                    WindowManager.LayoutParams wmParams=new WindowManager.LayoutParams();
                                    wmParams.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
                                    wmParams.format= PixelFormat.TRANSPARENT; //set the opacity to 100%
                                    wmParams.windowAnimations=android.R.style.Animation_Translucent;
                                    wm.addView(bigImage,wmParams);
                                    bigImage.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            wm.removeViewImmediate(bigImage);
                                        }
                                    });
                                    bigImage.setOnKeyListener(new View.OnKeyListener() {
                                        @Override
                                        public boolean onKey(View v, int keyCode, KeyEvent event) {
                                            wm.removeViewImmediate(bigImage);
                                            return true;
                                        }
                                    });
                                    bigImage.setOnLongClickListener(new View.OnLongClickListener() {
                                        @Override
                                        public boolean onLongClick(View v) {
                                            final PopupWindow popupWindow = new PopupWindow(getActivity());
                                            popupWindow.setBackgroundDrawable(getActivity().getDrawable(R.drawable.bg_shadow_white));
                                            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_download_menu,null,false);
                                            TextView download = view.findViewById(R.id.download);
                                            download.setOnClickListener(new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    if (downloadImage(headImageUri)){
                                                        Toast.makeText(getActivity(), "下载成功", Toast.LENGTH_SHORT).show();
                                                    } else {
                                                        Toast.makeText(getActivity(), "下载失败", Toast.LENGTH_SHORT).show();
                                                    }
                                                    popupWindow.dismiss();
                                                }
                                            });
                                            popupWindow.setContentView(view);
                                            popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                                            popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                                            popupWindow.setOutsideTouchable(true);
                                            popupWindow.showAsDropDown(bigImage,0,10);
                                            return true;
                                        }
                                    });
                                }
                            })
                    .show();

                }
            });
            refreshPic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.get(IdentityFragment.this.getActivity()).clearDiskCache();
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Glide.get(getActivity()).clearMemory();
                                    Toast.makeText(getActivity(), "刷新完成，重启以应用", Toast.LENGTH_SHORT).show();

                                }
                            });
//                            Log.d("kmh", "run: clear");
                            new Thread(userInfo).start();
                        }
                    }).start();
                }
            });
            changeAccount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder alertDeleteData = new AlertDialog.Builder(IdentityFragment.this.getActivity());
                    alertDeleteData.setTitle("切换用户");
                    alertDeleteData.setMessage("确定切换用户\n这将会注销当前用户");

                    alertDeleteData.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //删除所有有关数据库内容
                            try {
                                deleteImage.get(100, TimeUnit.MILLISECONDS);
                            } catch (Exception e){
                                e.printStackTrace();
                            }
                            Intent intent = new Intent(IdentityFragment.this.getActivity(), MainActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            startActivity(intent);
                            UserDataDao userDataDao = new UserDataDao();
                            userDataDao.logoutUser(username);
                            ActivityManage.removeAllActivityExcept("MainActivity");
                        }
                    });
                    alertDeleteData.setNegativeButton("取消",null);
                    alertDeleteData.show();
                }
            });
            exitAccount.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final AlertDialog.Builder alert = new AlertDialog.Builder(IdentityFragment.this.getActivity());
                    alert.setTitle("注销登录");
                    alert.setMessage("是否注销登录");
                    alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            AlertDialog.Builder alertDeleteData = new AlertDialog.Builder(IdentityFragment.this.getActivity());
                            alertDeleteData.setTitle("删除数据");
                            alertDeleteData.setMessage("是否删除所有个人数据");

                            alertDeleteData.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //删除所有有关数据库内容
                                    UserDataDao userDataDao = new UserDataDao();
                                    userDataDao.deleteUser(username);
                                    new Thread(deleteImage).start();
                                    try {
                                        deleteImage.get(100, TimeUnit.MILLISECONDS);
                                    } catch (Exception e){
                                        e.printStackTrace();
                                    }
                                    System.exit(0);
                                    ActivityManage.removeAllActivity();
                                }
                            });
                            alertDeleteData.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //开一个线程改变用户数据库
                                    UserDataDao userDataDao = new UserDataDao();
                                    userDataDao.logoutUser(username);
                                    try {
                                        deleteImage.get(100, TimeUnit.MILLISECONDS);
                                    } catch (Exception e){
                                        e.printStackTrace();
                                    }
                                    System.exit(0);
                                    ActivityManage.removeAllActivity();
                                }
                            });
                            alertDeleteData.show();
                        }
                    });
                    alert.setNegativeButton("取消", null);
                    alert.show();
                }
            });
        }
    }

    /**
     * 调用系统api选取头像
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1){
            if (data != null){
                final Uri imageUri = data.getData();
                if (imageUri != null && getActivity() != null){
                    ImageView imageView = new ImageView(getActivity());
                    imageView.setImageURI(imageUri);
                    imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
                    alert.setTitle("确定头像").setNegativeButton("取消",null).setView(imageView)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    updateHeadImage(imageUri);
                                }
                            }).show();
                }

            }
        }
    }

    /**
     * 获取数据，填充头像
     */
    private FutureTask<User> userInfo = new FutureTask<>(new Callable<User>() {
        @Override
        public User call() {
            try {
                Socket socket = new Socket("106.15.192.117", 2333);
                Gson gson = new Gson();
                User user = new User();
                user.setFlag(4);
                user.setUserName(TalkListActivity.username);
                user.setPassword(TalkListActivity.password);
                String message = gson.toJson(user);
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(message);
                dataOutputStream.flush();
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                String netStr = dataInputStream.readUTF();
                try {
                    JSONObject getMessage = new JSONObject(netStr);
                    if (getMessage.getInt("code") == -1){
                        throw new JSONException("服务器错误");
                    } else if (getMessage.getInt("code") == 0){
                        userData = gson.fromJson(getMessage.getString("data"),User.class);
                        if (userData != null && getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    headImageUri = Uri.parse(userData.getPic());
                                    Glide.with(getActivity())
                                            .load(userData.getPic())
                                            .into(headView);
                                }
                            });

                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                }

            } catch (Exception ioe) {
                ioe.printStackTrace();
            }
            return null;
        }
    });

    /**
     * 根据uri更新头像
     * @param imageUri
     */
    private void updateHeadImage(final Uri imageUri){
        try {
            ParcelFileDescriptor fileDescriptor = getActivity().getContentResolver().openFileDescriptor(imageUri,"r");
            FileDescriptor fd = fileDescriptor.getFileDescriptor();
            pictureIn = new FileInputStream(fd);//文件输入流
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int length;
                    byte[] sendBytes;
                    try {
                        Socket socket = new Socket("106.15.192.117", 2333);
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                        User user = new User();
                        user.setFlag(6);
                        user.setUserName(TalkListActivity.username);
                        user.setPassword(TalkListActivity.password);
                        dos.writeUTF(new Gson().toJson(user));
                        sendBytes = new byte[1024];
                        while ((length = pictureIn.read(sendBytes,0,sendBytes.length)) > 0) {
                            dos.write(sendBytes, 0, length);
                            dos.flush();
                        }
                        String result = dis.readUTF();
                        try {
                            final JSONObject getMessage = new JSONObject(result);
                            if (getMessage.getInt("code") == 0){
                                if (getActivity() != null){
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            try {
                                                ImageView im = getActivity().findViewById(R.id.BarImage);
                                                im.setMaxHeight(100);
                                                headImageUri = Uri.parse(getMessage.getString("data"));
                                                Glide.with(getActivity())
                                                        .load(imageUri)
                                                        .into(headView);
                                                Glide.with(getActivity())
                                                        .load(imageUri)
                                                        .into(im);
                                            } catch (Exception e){
                                                e.printStackTrace();
                                            }

                                        }
                                    });
                                    Looper.prepare();
                                    Toast.makeText(getActivity(),"上传成功",Toast.LENGTH_SHORT).show();
                                    Looper.loop();
                                }
                            } else {
                                Looper.prepare();
                                //出了任何异常都判定为上传失败
                                Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                            }//显示上传失败
                        } catch (JSONException e) {
                            Log.d("kmh", "doInBackground: 后端JSON字符串有问题祭天吧");
                        } finally {
                            Looper.prepare();
                            Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                            dis.close();
                            dos.close();
                            socket.close();
                        }

                    } catch (IOException ioe){
                        Looper.prepare();
                        Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                        Looper.loop();
                        ioe.printStackTrace();
                    }
                }
            }).start();
        } catch (Exception e){
            Looper.prepare();
            Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
            Looper.loop();
            e.printStackTrace();
        }
    }

    private FutureTask<Boolean> deleteImage= new FutureTask<>(new Callable<Boolean>() {
        @Override
        public Boolean call(){
            if (IdentityFragment.this.getActivity() != null){
                Glide.get(IdentityFragment.this.getActivity()).clearDiskCache();
                Glide.get(IdentityFragment.this.getActivity()).clearMemory();
            }
            return true;
        }
    });

    private boolean downloadImage(final Uri uri) {
        if (getActivity() != null){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
            final String format = sdf.format(new Date());
            final FileOutputStream fileOS;
            try {
                final File file = new File(Environment
                        .getExternalStorageDirectory().toString()
                        + "/ProjectX/"
                        + format
                        + ".png");
                fileOS = new FileOutputStream(file);
                FutureTask<Boolean> futureTask = new FutureTask<>(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        try {
                            FileInputStream fileInputStream = new FileInputStream(Glide.with(getActivity()).load(uri).downloadOnly(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL).get());
                            byte[] bytes = new byte[1024];
                            while (fileInputStream.read(bytes,0,bytes.length) != -1){
                                fileOS.write(bytes);
                                fileOS.flush();
                            }
                            getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
                            return true;
                        } finally {
                            fileOS.close();
                        }

                    }
                });
                new Thread(futureTask).start();
                try {
                    return futureTask.get();
                } catch (Exception e){
                    Log.d("kmh", "Identity save: 保存出错");
                }

            } catch (IOException e){
                e.printStackTrace();
                Log.d("kmh", "Identity save: io错误");
                return false;
            }
            return false;
        }
        return false;
    }
}
